import sys
import csv
import pandas as pd
from PyQt5 import QtCore, QtGui
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import pyqtSlot

from view.Ui_mainWindow import Ui_MainWindow

from person import Person


# 读取文件中存储的用户名与密码
def readAdminInfo(filename="data/admin.txt"):
    with open(filename, 'r+', encoding='utf-8') as f:
        s = [i[:-1].split(',') for i in f.readlines()]  # 读取文件里的每行文本
        return s  # 返回所有读取到的用户名和密码


class MainWindow(QMainWindow, Ui_MainWindow):  # 多重继承QMainWindow和Ui_MainWindow
    def __init__(self):
        super(MainWindow, self).__init__()  # 先调用父类QMainWindow的初始化方法
        self.setupUi(self)
        self.initUI()  # 再调用setupUi方法

    def initUI(self):
        # 利用tableWidget展示数据
        self.vipList.setColumnCount(7)  # 表格设置为7列
        headers = ['编号', '姓名', '密码', '性别', '生日', '会员等级', '积分']  # 表格标题栏
        self.vipList.setHorizontalHeaderLabels(headers)  # 表格设置标题栏
        # 下面两行用于设置列宽自适应
        self.vipList.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.vipList.horizontalHeader().setSectionResizeMode(0, QHeaderView.ResizeToContents)
        # 隐藏默认行号
        self.vipList.verticalHeader().setHidden(True)
        # tableWidget 进行排序
        self.vipList.setSortingEnabled(True)

        # 从vip_data.csv中读取数据
        vip_list = pd.read_csv(r'data/vip_data.csv', header=None, encoding='utf-8')
        for vip in vip_list.itertuples():
            self.add_line(vip)

        # 从admin.txt中读取数据
        info_list = readAdminInfo()
        self.nameInput.setText(info_list[0][0])
        self.pwdInput.setText(info_list[0][1])

    # tableWidget 添加行信息的方法封装
    def add_line(self, vip):
        rowCount = self.vipList.rowCount()  # 取表格当前行数
        self.vipList.setRowCount(rowCount + 1)  # 表格增加一行
        for i in range(7):  # 循环处理vip_data的6个数据
            item = QTableWidgetItem(str(vip[i + 1]))  # 从vip中取一个数据

            item.setTextAlignment(QtCore.Qt.AlignCenter)  # 设置单元格内容居中
            self.vipList.setItem(rowCount, i, item)  # 指定单元格和行和列,以及数据

    # 搜索功能的实现
    @pyqtSlot()
    def on_searchBtn_clicked(self):
        try:
            text = self.searchInput.text()  # 获取搜索文本
            items = self.vipList.findItems(text, QtCore.Qt.MatchExactly)  # 搜索模式为完全匹配
            row = items[0].row()  # 获取搜索到的行号
            self.vipList.selectRow(row)  # 选中对应行
        except:
            QMessageBox.information(self, '提示信息', '未查询到相关数据!')

    # 添加功能
    @pyqtSlot()
    def on_addBtn_clicked(self):
        count = self.vipList.rowCount()  # 获取总行数
        self.vipList.setRowCount(count + 1)  # 添加1行

        num = self.vipList.item(count - 1, 0).text()  # 获取上一行的序号

        for i in range(7):
            item = QTableWidgetItem()  # 创建单元格
            item.setTextAlignment(QtCore.Qt.AlignCenter)  # 居中
            self.vipList.setItem(count, i, item)  # 设置单元格的值

        newNum = int(num) + 1
        self.vipList.item(count, 0).setText(str(newNum))

        defaultLevel = "普卡"  # 默认等级
        self.vipList.item(count, 5).setText(defaultLevel)  # 设置默认等级

        defaultScore = "0"  # 默认积分
        self.vipList.item(count, 6).setText(defaultScore)  # 设置默认积分

    # 删除功能
    @pyqtSlot()
    def on_delBtn_clicked(self):
        try:
            items = self.vipList.selectedItems()  # 获取选中行
            item = items[0]  # 默认单选
            self.vipList.removeRow(item.row())  # 删除指定行
        except:
            QMessageBox.information(self, '提示信息', '请选中要操作的数据的编号!')

    # 等级查询功能
    @pyqtSlot()
    def on_levelBtn_clicked(self):
        try:
            text = self.levelCombox.currentText()  # 获取选择框的值
            count = self.vipList.columnCount()  # 全部行数
            if text == "全部":
                for i in range(count):
                    self.vipList.showRow(i)
            else:
                items = self.vipList.findItems(text, QtCore.Qt.MatchExactly)  # 搜索模式为完全匹配
                # 隐藏所有的行
                for i in range(count):
                    self.vipList.hideRow(i)
                # 将满足查找条件的行显示
                for item in items:  # 匹配到的单元格对象
                    self.vipList.showRow(item.row())  # 只显示查找到的行
        except:
            QMessageBox.information(self, '提示信息', '请选中要操作的数据的编号!')

    # 积分+10
    @pyqtSlot()
    def on_addScoreBtn_clicked(self):
        try:
            items = self.vipList.selectedItems()  # 获取选中行
            item = items[0]  # 默认单选
            score = self.vipList.item(item.row(), 6).text()  # 获取选中行的积分
            newScore = int(score) + 10  # 计算新的积分
            newLevel = self.checkScore(newScore)  # 计算新积分对应的等级
            self.vipList.item(item.row(), 6).setText(str(newScore))  # 积分+10
            self.vipList.item(item.row(), 5).setText(str(newLevel))  # 设置积分对应的等级
        except:
            QMessageBox.information(self, '提示信息', '请选中要操作的数据的编号!')

    # 积分-10
    @pyqtSlot()
    def on_reduceScoreBtn_clicked(self):
        try:
            items = self.vipList.selectedItems()  # 获取选中行
            item = items[0]  # 默认单选
            score = self.vipList.item(item.row(), 6).text()  # 获取选中行的积分
            newScore = int(score) - 10  # 计算新的积分
            newLevel = self.checkScore(newScore)  # 计算新积分对应的等级
            if newScore < 0:
                QMessageBox.information(self, '提示信息', '积分最多减少到0!')
                newScore = 0
            self.vipList.item(item.row(), 6).setText(str(newScore))  # 积分-10
            self.vipList.item(item.row(), 5).setText(str(newLevel))  # 设置积分对应的等级
        except:
            QMessageBox.information(self, '提示信息', '请选中要操作的数据的编号!')

    # 清空积分
    @pyqtSlot()
    def on_clearScoreBtn_clicked(self):
        try:
            items = self.vipList.selectedItems()  # 获取选中行
            item = items[0]  # 默认单选
            self.vipList.item(item.row(), 6).setText("0")  # 积分设置为0
            self.vipList.item(item.row(), 5).setText("普卡")  # 设置积分对应的等级
        except:
            QMessageBox.information(self, '提示信息', '请选中要操作的数据的编号!')

    # 提升等级
    @pyqtSlot()
    def on_improveLevelBtn_clicked(self):
        try:
            items = self.vipList.selectedItems()  # 获取选中行
            item = items[0]  # 默认单选
            level = self.vipList.item(item.row(), 5).text()  # 获取积分对应的等级
            if level == "普卡":
                level = "银卡"
                self.vipList.item(item.row(), 6).setText("100")
            elif level == "银卡":
                level = "金卡"
                self.vipList.item(item.row(), 6).setText("200")
            elif level == "金卡":
                level = "白金卡"
                self.vipList.item(item.row(), 6).setText("300")
            elif level == "白金卡":
                level = "黑卡"
                self.vipList.item(item.row(), 6).setText("400")
            elif level == "黑卡":
                level = "至尊VIP"
                self.vipList.item(item.row(), 6).setText("500")
            elif level == "至尊VIP":
                QMessageBox.information(self, '提示信息', '已经提升到最高等级!')
            self.vipList.item(item.row(), 5).setText(level)
        except:
            QMessageBox.information(self, '提示信息', '请选中要操作的数据的编号!')

    # 重写关闭时的事件,保存数据
    def closeEvent(self, event):
        reply = QMessageBox.question(self, '提示信息', '确认要关闭窗口？',
                                     QMessageBox.Yes | QMessageBox.No,
                                     QMessageBox.No)
        if reply == QMessageBox.Yes:
            event.accept()
            self.saveTableDataToCSV()  # 保存表格数据到本地文件
            self.saveAdminInfo()  # 保存管理员数据
        else:
            event.ignore()

    # 对应分数对应的等级
    def checkScore(self, score):
        if 0 < score < 100:
            return "普卡"
        elif 100 <= score < 200:
            return "银卡"
        elif 200 <= score < 300:
            return "金卡"
        elif 300 <= score < 400:
            return "白金卡"
        elif 400 <= score < 500:
            return "黑卡"
        elif 500 <= score:
            return "至尊VIP"

    # 将tableWidget数据保存到csv
    def saveTableDataToCSV(self, filename="data/vip_data.csv"):
        row = self.vipList.rowCount()
        column = self.vipList.columnCount()
        with open(filename, "w", encoding="utf-8", newline="") as f:
            writer = csv.writer(f)  # 初始化写入对象
            for i in range(row):
                row_list = []
                for j in range(column):
                    row_list.append(self.vipList.item(i, j).text())
                writer.writerow(row_list)

    # 将管理员数据保存到txt
    def saveAdminInfo(self, filename="data/admin.txt"):
        with open(filename, "w", encoding="utf-8") as f:
            f.write("%s,%s\n" % (self.nameInput.text(), self.pwdInput.text()))


if __name__ == '__main__':
    app = QApplication(sys.argv)
    # app.setStyle(QStyleFactory.create("Fusion"))
    ui = MainWindow()
    ui.show()
    sys.exit(app.exec_())
